package com.kcwl.carrier.application.service;

import com.kcwl.carrier.domain.service.CarrierCollectionDomainService;
import com.kcwl.carrier.infrastructure.constant.CarrierConstant;
import com.kcwl.carrier.infrastructure.enums.CarrierCollectionErrorCodeEnum;
import com.kcwl.carrier.infrastructure.enums.CarrierCollectionIsDelCodeEnum;
import com.kcwl.carrier.infrastructure.exceptions.CarrierCollectionException;
import com.kcwl.carrier.infrastructure.repository.po.CarrierCollectionCompanyInfoPO;
import com.kcwl.carrier.infrastructure.utils.DateUtil;
import com.kcwl.carrier.infrastructure.utils.SysUtil;
import com.kcwl.carrier.interfaces.command.CarrierCompanyCommand;
import com.kcwl.carrier.interfaces.dto.CarrierCollectionCompanyInfoDTO;
import com.kcwl.carrier.interfaces.query.CarrierCompanyQuery;
import com.kcwl.ddd.application.constants.YesNoEnum;
import com.kcwl.ddd.infrastructure.api.ResponseMessage;
import com.kcwl.ddd.infrastructure.session.SessionContext;
import com.kcwl.ddd.interfaces.dto.PageResultDTO;
import com.kcwl.framework.lock.DistributedLocker;
import com.kcwl.partner.interfaces.api.IDeptService;
import com.kcwl.partner.interfaces.api.IEnterpriseService;
import com.kcwl.partner.interfaces.dto.AggDepartmentDTO;
import com.kcwl.partner.interfaces.dto.EnterpriseDTO;
import com.kcwl.partner.interfaces.query.EnterpriseQuery;
import com.kcwl.partner.interfaces.query.SysDepartmentConditionQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 张志强
 * 货主收藏
 */
@Service
public class CarrierCollectionApplicationService {
    @Autowired
    CarrierCollectionDomainService carrierCollectionDomainService;
    @Autowired
    DistributedLocker locker;
    @Autowired
    IDeptService iDeptService;
    @Autowired
    IEnterpriseService iEnterpriseService;
    /**
     * 收藏信息部前缀
     */
    public static final String LOCK_KEY_PREFIX_COLLECT_COMPANY = "collect_company_info_";
    /**
     * 添加黑名单
     */
    public Boolean addOrUpdateCollectEnterprise(CarrierCompanyCommand carrierCompanyCommand)throws CarrierCollectionException {
        Long userId = carrierCompanyCommand.getUserId();
        Long departmentId = carrierCompanyCommand.getDepartmentId();
        String key  = LOCK_KEY_PREFIX_COLLECT_COMPANY + (userId+departmentId);
        try{
            boolean lock = locker.tryLock(key, TimeUnit.SECONDS, 3,  5);
            if (!lock) {
                throw new CarrierCollectionException(CarrierCollectionErrorCodeEnum.OPERATE_FAIL);
            }
            CarrierCompanyQuery query = new CarrierCompanyQuery();
            query.setUserId(carrierCompanyCommand.getUserId());
            query.setDepartmentId(carrierCompanyCommand.getDepartmentId());
            CarrierCollectionCompanyInfoPO carrierCollectionCompanyInfoPO = carrierCollectionDomainService.getCarrierCompany(query);
            if(null!=carrierCollectionCompanyInfoPO){
                if (carrierCollectionCompanyInfoPO.getIsDel().equals(SysUtil.parseByte(CarrierCollectionIsDelCodeEnum.YES.getCode()))){
                    throw new CarrierCollectionException(CarrierCollectionErrorCodeEnum.DEPARTMENT_IS_EXIST);
                }else{
                    CarrierCompanyCommand command = new CarrierCompanyCommand();
                    command.setId(carrierCollectionCompanyInfoPO.getId());
                    command.setRemark("用户："+userId+" 【"+ DateUtil.getCurDate()+ " 】重新置为生效！");
                    command.setUpdateTime(new Date());
                    command.setUpdateUserId(userId);
                    command.setIsDel(SysUtil.parseByte(CarrierCollectionIsDelCodeEnum.YES.getCode()));
                    int num = carrierCollectionDomainService.updateCarrierCompany(command);
                    if(num == 0){
                        throw new CarrierCollectionException(CarrierCollectionErrorCodeEnum.COLLECTION_FAIL);
                    }
                }
            }else{
                CarrierCompanyQuery queryList = new CarrierCompanyQuery();
                queryList.setUserId(carrierCompanyCommand.getUserId());
                List<CarrierCollectionCompanyInfoDTO> collectShippers = carrierCollectionDomainService.getCollectShippers(queryList);
                if(collectShippers.size() > CarrierConstant.CARRIER_COLLECTION_LIMIT){
                    throw new CarrierCollectionException(CarrierCollectionErrorCodeEnum.SUM_SIZE);
                }
                Date now = new Date();
                CarrierCompanyCommand command = new CarrierCompanyCommand();
                command.setUserId(userId);
                command.setCreateTime(now);
                command.setCreateUserId(userId);
                command.setDepartmentId(carrierCompanyCommand.getDepartmentId());
                command.setEnterpriseId(carrierCompanyCommand.getEnterpriseId());
                command.setDataSource(YesNoEnum.NAY.getValue());
                command.setUpdateTime(now);
                command.setUpdateUserId(userId);
                command.setIsDel(SysUtil.parseByte(CarrierCollectionIsDelCodeEnum.YES.getCode()));
                command.setRemark("用户："+userId+" 【"+DateUtil.getCurDate()+ " 】收藏信部门id"+departmentId );
                command.setDataSource(1);
                int num = carrierCollectionDomainService.addCarrierCompany(command);
                if(num == 0){

                    throw new CarrierCollectionException(CarrierCollectionErrorCodeEnum.COLLECTION_FAIL);
                }
            }
        }finally {
            locker.unlock(key);
        }
        return true;
    }

    /**
     * 司机已经收藏货主集合
     */
    public List<CarrierCollectionCompanyInfoDTO> getCollectShippers(CarrierCompanyQuery query)throws CarrierCollectionException {
        List<CarrierCollectionCompanyInfoDTO> list = carrierCollectionDomainService.getCollectShippers(query);
        SysDepartmentConditionQuery sysDepartmentConditionQuery = new SysDepartmentConditionQuery();
        sysDepartmentConditionQuery.setIdList(list.stream().map(CarrierCollectionCompanyInfoDTO::getDepartmentId).collect(Collectors.toList()));
        sysDepartmentConditionQuery.setCurPagerNo(1);
        sysDepartmentConditionQuery.setPageSize(list.size());
        ResponseMessage<PageResultDTO<AggDepartmentDTO>> resultDTOResponseMessage = iDeptService.selectDeptWithEnterprise(sysDepartmentConditionQuery);
        Map<Long,AggDepartmentDTO> aggListMap = resultDTOResponseMessage.getResult().getPage().getList().stream().collect(Collectors.toMap(AggDepartmentDTO::getDepartmentId, Function.identity()));
        EnterpriseQuery enterpriseQuery = new EnterpriseQuery();
        enterpriseQuery.setIdList(list.stream().filter(v->v.getEnterpriseId()!=null).map(CarrierCollectionCompanyInfoDTO::getEnterpriseId).collect(Collectors.toList()));
        ResponseMessage<List<EnterpriseDTO>> enterpriseList = iEnterpriseService.queryEnterpriseList(enterpriseQuery);
        Map<Long,EnterpriseDTO> enterpriseDTOMap = enterpriseList.getResult().stream().collect(Collectors.toMap(EnterpriseDTO::getId, Function.identity()));
        list.stream().forEach(v->{
            if(aggListMap.get(v.getDepartmentId())!=null){
                v.setDeptName(aggListMap.get(v.getDepartmentId()).getDeptName());
                v.setEnterpriseName(aggListMap.get(v.getDepartmentId()).getEnterpriseName());
            }
            if(enterpriseDTOMap.get(v.getEnterpriseId())!=null){
                v.setPlatformNo(enterpriseDTOMap.get(v.getEnterpriseId()).getPlatformNo());
            }
        });
        return list;
    }

    /**
     * 取消货主收藏
     */
    public int cancelShipperCollection(CarrierCompanyCommand command)throws CarrierCollectionException {
        CarrierCompanyQuery query = new CarrierCompanyQuery();
        query.setDepartmentId(command.getDepartmentId());
        query.setUserId(SessionContext.getSessionData().getUserId());
        CarrierCollectionCompanyInfoPO carrierCollectionCompanyInfoPO = carrierCollectionDomainService.getCarrierCompany(query);
        command.setId(carrierCollectionCompanyInfoPO.getId());
        command.setIsDel(SysUtil.parseByte(YesNoEnum.YEA.getValue()));
        command.setRemark("用户："+query.getUserId()+" 【"+ DateUtil.getCurDate()+ " 】置为失效！");
        return carrierCollectionDomainService.updateCarrierCompany(command);
    }

    /**
     * 根据条件查询收藏数量
     */
    public int getCollectCount(CarrierCompanyQuery  query)throws CarrierCollectionException {
        return carrierCollectionDomainService.getCollectCount(query);
    }

}
